package cn.zx.rmq.producer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Package: cn.zx.rmq.producer
 * @ClassName: SyncProducer
 * @Author: Think
 * @CreateTime: 2021/6/28 10:58
 * @Description: producer的主线程只发送了一次，就将所有的消息都发送给了MQ，MQ还是会把集合中的消息拆出来，单独进行存储。
 * 所以消费者消费的时候，还是会对单个消息进行消费，而不是对整个集合进行消费。
 */
@Slf4j
public class BatchProducer {

    public static void main(String[] args) throws MQClientException, MQBrokerException, RemotingException, InterruptedException, UnsupportedEncodingException {
        DefaultMQProducer producer = new DefaultMQProducer("SyncProducer-Group");
        producer.setNamesrvAddr("localhost:9876");
        producer.start();

        List<Message> messageList = new ArrayList<>();
        Message msg1 = new Message("KYC", "about-order", "123", ("zhangsan下单了").getBytes(RemotingHelper.DEFAULT_CHARSET));
        Message msg2 = new Message("KYC", "about-order", "125", ("lisi下单了").getBytes(RemotingHelper.DEFAULT_CHARSET));
        Message msg3 = new Message("KYC", "about-order", "123", ("zhangsan收货了").getBytes(RemotingHelper.DEFAULT_CHARSET));
        Message msg4 = new Message("KYC", "about-order", "125", ("lisi收货了").getBytes(RemotingHelper.DEFAULT_CHARSET));
        Message msg5 = new Message("KYC", "about-order", "125", ("lisi评价了").getBytes(RemotingHelper.DEFAULT_CHARSET));
        Message msg6 = new Message("KYC", "about-order", "123", ("zhangsan评价了").getBytes(RemotingHelper.DEFAULT_CHARSET));
        messageList.add(msg1);
        messageList.add(msg2);
        messageList.add(msg3);
        messageList.add(msg4);
        messageList.add(msg5);
        messageList.add(msg6);

        // 集合总大小不能超过4M
        SendResult sendResult = producer.send(messageList);
        log.info("发送返回信息为：{}", sendResult);

        producer.shutdown();
        log.info("所有消息发送完毕！");
    }

}
